//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    logs:[],
    initJe: 1000,
    expProfit:1030,
    countValue: 0
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      expProfit: e.detail.value
    })
  },
  betting: function(){
    console.log("betting...")
    this.data.countValue = 0    
    var firstJe = 1 //第一次投注金额
    var betJe = firstJe //下注金额
    var maxJe = betJe  //最大下注金额
    var currentJe = this.data.initJe //当前余额
    var minJe = currentJe //最小当前余额
    var _log = ""
    
    console.log("currentJe: " + currentJe + ", expProfit: " + this.data.expProfit)
    while (currentJe > 0 && currentJe < this.data.expProfit){
      this.data.countValue++
      //console.log(new Date() + " " + this.data.countValue)
      var d = this.dice()//摇骰子，生成“大”或“小”    
      this.sleep(500)//思考0.5秒
      var bet = this.dice()//下注
      if(betJe > maxJe){
        maxJe = betJe
      }
      if(currentJe < minJe){
        minJe = currentJe
      }
      _log = "第" + this.data.countValue + "次投注"
      if (d === bet){
        _log += "win，下注金额：" + betJe
        currentJe += betJe
        betJe = firstJe
      }
      else{
        _log += "false，下注金额：" + betJe
        currentJe -= betJe
        betJe *= 2
      }
      _log += " 当前金额：" + currentJe
      console.log(_log)
      
      this.data.logs.push(_log)
      this.setData({
        countValue: this.data.countValue,
        info: _log
      })      
    }    
    _log += "\n本轮投注最高金额：" + maxJe + ", 最低金额：" + minJe
    console.log(_log)
    this.setData({
      info: _log
    })
  },
  
  dice:function(){    
    return Math.random() >= 0.5 ? "big" :"small"
  },
  sleep:function(d){
    //console.log("sleep " + d + "ms")

    for(var t = Date.now();Date.now() - t <= d;){}
  }
})
